<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 用户竞答总数据（取一天中的最高的一轮来计算）表
 */

class AnswerActivityUserCorrectTotalNumber extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_correct_total_number';

    /**
     * 获取用户单位答题总记录
     */
    public function getAnswerTotelData($act_id, $unit_id, $user_guid)
    {

        $unit_id = $unit_id ?: 0;
        $res = $this->where('user_guid', $user_guid)->where('act_id', $act_id)->where('unit_id', $unit_id)->first();
        if (empty($res)) {
            return [];
        }
        //这个表是区每轮最好成绩，改为取记录表，然后相加
        $res['answer_number'] = AnswerActivityUserCorrectAnswerRecord::where('user_guid', $user_guid)
        ->where('act_id', $act_id)
        ->where(function($query) use($unit_id){
            if($unit_id){
                $query->where('unit_id', $unit_id);//这里 0 也算不存在
            }
        })
        ->count();
        return $res;
    }

    /**
     * 写入总轮次记录，只取每日最高一次来做记录
     * @param  pattern 答题模式  1  馆内答题形式  2 轮次排名形式 （按轮次排名）  3 爬楼梯形式
     */
    public function addUserCorrectTotalNumber($act_id, $unit_id, $user_guid, $answer_number, $answer_time, $node = 1, $exclude_correct_number_id = null)
    {
        $res = $this->getCorrectTotelData($act_id, $unit_id, $user_guid);

        $activityUserCorrectNumber = new AnswerActivityUserCorrectNumber();
        $date = date('Y-m-d');
        $new_res = $activityUserCorrectNumber->getCorrectNumber($act_id, $unit_id, $user_guid, $date, 'correct_number desc , `times` asc', $exclude_correct_number_id, 1); //获取当日一次答题记录

        if ($res && $new_res) {
            $res->times = $res->times + $answer_time - $new_res[0]['times'];
            $res->save();

            //  return true; //有记录就不用在操作，等操作完成后，自动更新
        } else if ($res && empty($new_res)) {
            $res->answer_number = $res->answer_number + $answer_number; //只在每日第一次参加活动时增加

            $res->times = $res->times + $answer_time;

            $res->save();
        } else {
            $obj = new self();
            $obj->act_id = $act_id;
            $obj->unit_id = $unit_id ?: 0;
            $obj->user_guid = $user_guid;
            $obj->answer_number = $answer_number;
            $obj->correct_number = 0;
            $obj->accuracy = 0;
            $obj->times = $answer_time;
            $obj->save();
        }

        if ($node != 1 && !empty($unit_id)) {
            $this->addUserCorrectTotalNumber($act_id, 0, $user_guid, $answer_number, $answer_time, 1, $exclude_correct_number_id); //如果不是独立活动，还要在记录一次总排名
        }

        return $this->id;
    }

    /**
     * 修改总轮次记录，只取每日最高一次来做记录
     * @param  node 活动类型    1 独立活动  2 单位联盟   3 区域联盟   
     */
    public function changeUserCorrectTotalNumber($act_id, $unit_id, $user_guid, $answer_time, $node = 1)
    {
        $unit_id = $unit_id ?: 0;
        $activityUserCorrectNumber = new AnswerActivityUserCorrectNumber();
        $date = date('Y-m-d');
        $new_res = $activityUserCorrectNumber->getCorrectNumber($act_id, $unit_id, $user_guid, $date, 'id desc', null, 1); //获取最新一次答题记录
        $max_res = $activityUserCorrectNumber->getCorrectNumber($act_id, $unit_id, $user_guid, $date, 'correct_number desc , `times` asc', null, 2); //获取正确率最高两次答题记录
        // Log::error($new_res);
        // Log::error($max_res);

        if (empty($new_res) || empty($max_res)) {
            return false;
        }
        $correctTotelData = $this->getCorrectTotelData($act_id, $unit_id, $user_guid);

        $high_record = $max_res[0];
        $count = count($max_res);
        $correct_number = $correctTotelData->correct_number; //原有次数
        // $times = $correctTotelData->times;//原有时长

        if ($count == 1) {
            Log::error(1);
            $correct_number = $correctTotelData->correct_number + $high_record['correct_number']; //新增数量，就是对的数量
            $times = $correctTotelData->times - $answer_time + $high_record['times']; //总答题时长

        } /* elseif ($high_record['correct_number'] < $new_res[0]['correct_number']) {
            Log::error(2);
            $correct_number = $correctTotelData->correct_number - $max_res[1]['correct_number'] + $new_res[0]['correct_number']; //获取新增对的数量
            $times = $correctTotelData->times - $max_res[1]['times'] + $new_res[0]['times']; //使用答题时间短的一次作为答题时长
            //$times = $correctTotelData->times - $max_res[1]['times'] + $new_res[0]['times']; //使用答题时间短的一次作为答题时长
        } */ elseif ($high_record['correct_number'] == $new_res[0]['correct_number']) {
            //  Log::error(2);
            $correct_number = $correctTotelData->correct_number - $max_res[1]['correct_number'] + $new_res[0]['correct_number']; //获取新增对的数量
            if ($high_record['times'] < $new_res[0]['times']) {
                $times = $correctTotelData->times - $answer_time + $high_record['times']; //使用答题时间短的一次作为答题时长
            } else {
                $times = $correctTotelData->times - $answer_time + $new_res[0]['times']; //使用答题时间短的一次作为答题时长
            }
        } else {
            //  Log::error(3);
            //时间不变
            $times = $correctTotelData->times - $answer_time + $max_res[0]['times']; //使用答题时间短的一次作为答题时长
        }

        //只有一条，默认就是最多的那条
        // $correctTotelData->answer_number = $correctTotelData->answer_number + $high_record['answer_number']; //前面已增加总答题数
        $correctTotelData->correct_number = $correct_number;

        $accuracy = $correctTotelData->correct_number / $correctTotelData->answer_number;
        $accuracy = sprintf("%.2f", $accuracy * 100);
        $correctTotelData->accuracy = $accuracy;
        $correctTotelData->times = $times;
        $correctTotelData->save();


        if ($node != 1 && !empty($unit_id)) {
            $this->changeUserCorrectTotalNumber($act_id, 0, $user_guid, $answer_time, 1); //如果不是单位活动，还需要单独新建一条总活动的排名
        }

        return $high_record; //返回最高一次的记录
    }

    /**
     * 判断 今日上一次是否主动提交，没有需要手动提交一次
     *
     * @param $act_id  活动id
     * @param $answer_time 答题时间
     * @param $user_guid 用户id
     * @param $node 活动类型    1 独立活动  2 单位联盟   3 区域联盟   
     * @return void
     */
    public function lastCorrectGuestPosting($act_id, $user_guid = null, $answer_time = null, $answer_number = null, $node = null)
    {
        $last_data = AnswerActivityUserCorrectNumber::where('act_id', $act_id)->where(function ($query) use ($user_guid) {
            if ($user_guid) {
                $query->where('user_guid', $user_guid);
            } else {
                $query->where('expire_time', '<', date('Y-m-d H:i:s', strtotime('-2 min')));
            }
        })->where('date', date('Y-m-d'))
            ->where('status', 0)
            ->get();

        if ($last_data) {
            if (empty($answer_time) || empty($node) || empty($answer_number)) {
                $act_info = AnswerActivity::where('id', $act_id)->where('is_del', 1)->first();
                if (empty($act_info)) {
                    return false;
                }
                $answer_time = $act_info['act_info'];
                $node = $act_info['node'];
                $answer_number = $act_info['answer_number'];
            }

            foreach ($last_data as $key => $val) {
                //修改用户当次答题记录和概率 
                $activityUserCorrectNumber = new AnswerActivityUserCorrectNumber();
                $activityUserCorrectNumber->changeUserCorrectNumber($val, 0, $answer_number, $val['times']);

                $this->changeUserCorrectTotalNumber($act_id, $val['unit_id'], $val['user_guid'], $answer_time, $node);
            }
        }
    }
    /**
     * 获取用户单位答题总记录
     */
    public function getCorrectTotelData($act_id, $unit_id, $user_guid)
    {
        $unit_id = $unit_id ?: 0;
        return $this->where('user_guid', $user_guid)->where('act_id', $act_id)->where('unit_id', $unit_id)->first();
    }
}
